﻿Function Fix-Invalid ([array] $BadUser) {
	#Set-PSDebug -Step
	foreach ($Recip in $BadUser) {
		$attributeHash =  @{}
		$user = Get-QADObject $Recip.DistinguishedName -IncludedProperties C,MailNickName
		
		if ($Recip.RecipientType -like "User*") {
			if (-not $user.UserPrincipalName.Contains("@")) {
				$attributeHash["UserPrincipalName"] = "$($user.UserPrincipalName)@chw.edu"
			}
		}
		
		if ($Recip.RecipientType -eq "Mailuser" ) {
			if ($Recip.ExternalEmailAddress -eq $null ) {
				$attributeHash["TargetAddress"] = "SMTP:" + $Recip.WindowsEmailAddress
			}
		}
		
		if ($user.C.length -gt 2 ) {
			switch ($user.C) {
				"USA" {$attributeHash["C"] = "US";break}
				default {$attributeHash["C"] = "US"}
			}
		}
		
		if ($user.Displayname[0] -eq " " -or $user.Displayname.EndsWith(" ")) {
			$attributeHash["Displayname"] = $user.Displayname.Trim()
		}
		
		if ($Recip.RecipientType -ne "User") {
			if ($user.MailNickName.Contains(" ")) {
				$attributeHash["MailNickName"] = $user.MailNickName.Replace(" ",".")
			}
			if ($user.MailNickName.Contains("(")) {
				$attributeHash["MailNickName"] = $user.MailNickName.Replace("(","_")
			}
			if ($user.MailNickName.Contains(")")) {
				$attributeHash["MailNickName"] = $user.MailNickName.Replace(")","_")
			}
			if ($user.MailNickName.Contains(",")) {
				$attributeHash["MailNickName"] = $user.MailNickName.Replace(",",".")
			}
		}
		
		Set-QADObject $Recip.DistinguishedName -ObjectAttributes $attributeHash 
	}
	Set-PSDebug -Off
}
